package com.atnoce.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import vip.onepass.model.ColudUser;
import vip.onepass.model.DirType;
import vip.onepass.model.OnepassConfig;
import vip.onepass.model.PassItem;
import vip.onepass.model.SyncResult;
import vip.onepass.model.SynchHead;
import vip.onepass.service.ColudService;
import vip.onepass.service.SyncService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

@Controller
@RequestMapping(value="synch")
public class SyncController {

	@Autowired
	private SyncService syncService;
	@Autowired
	private ColudService coludService;
	private Map<String,Object> retMap;
	private String msg;
	private boolean flag;
	public SyncController(){
		retMap=new HashMap<String,Object>();
		msg="error";
		flag=false;
	}
	/**
	 * 同步服务头信息
	 * @param data
	 * @param response
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value="syncHend")
	@ResponseBody
	public String syncHend(String data,HttpServletResponse response){
		System.out.println("收到数据："+data);
		SyncResult result=new SyncResult();
		try{
			if(StringUtils.isNotEmpty(data)){
				List insertList=new ArrayList();
				List updateList=new ArrayList();
				
				SynchHead parseObject = JSON.parseObject(data,SynchHead.class);
				List content = parseObject.getContent();
				String account = parseObject.getAccount();
				ColudUser user = coludService.findByUserName(account);
				if(user==null){
					flag=false;
					msg="账号不存在!";
				}else{
					if(StringUtils.equals("config", parseObject.getObjType())){
						//如果是在同步配置
						final OnepassConfig onepassConfig = syncService.findOnepassConfigByUser(user.getColudId());
						if(content==null||content.size()==0){
							//客户端没有数据
							result.setInsert(true);
							insertList.add(onepassConfig);
							//result.setInsertContent(new ArrayList(){{add(onepassConfig);}});
						}else if(onepassConfig==null){//没有找到，插入
							OnepassConfig config = JSON.toJavaObject((JSONObject) content.get(0), OnepassConfig.class);
							config.setC_id(UUID.randomUUID().toString());
							config.setColud_id(user.getColudId());
							syncService.save(config);
						}else{
							OnepassConfig config = JSON.toJavaObject((JSONObject) content.get(0), OnepassConfig.class);
							if(config==null){
								//客户端没有数据
								result.setInsert(true);
								insertList.add(onepassConfig);
							}else{
								if(Long.parseLong(config.getModifyTime())>Long.parseLong(onepassConfig.getModifyTime())){
									//客户端为最新，更新服务器
									syncService.delConfig(user.getColudId());
									config.setC_id(UUID.randomUUID().toString());
									config.setColud_id(user.getColudId());
									syncService.save(config);
								}else if(Long.parseLong(config.getModifyTime())<Long.parseLong(onepassConfig.getModifyTime())){
									//服务器为最新，更新客户端
									result.setUpdate(true);
									updateList.add(onepassConfig);
								}
							}
							
						}
						
					}else if(StringUtils.equals("dir", parseObject.getObjType())){
						List<DirType> dirList = syncService.findAllDirByColudid(user.getColudId());
						//如果是在同步分类
						if(content==null||content.size()==0){
							//客户端没有数据
							result.setInsert(true);
							insertList.addAll(dirList);
						}else if(dirList==null||dirList.size()==0){
							//没有找到分类，插入
							for(Object o:content){
								DirType javaObject = JSON.toJavaObject((JSONObject)o, DirType.class);
								javaObject.setColud_id(user.getColudId());
								javaObject.setD_id(UUID.randomUUID().toString());
								syncService.saveDir(javaObject);
							}
						}else{
							//合并集合
							List<DirType> allData=new ArrayList<DirType>();
							allData.addAll(dirList);
							List<DirType> clientData=new ArrayList<DirType>();
							for(Object o:content){
								DirType javaObject = JSON.toJavaObject((JSONObject)o, DirType.class);
								allData.add(javaObject);
								clientData.add(javaObject);
							}
							DirType dt;
							//处理客户端数据
							c:for(DirType d:allData){
								for(DirType c:clientData){
									if(StringUtils.equals(d.getDirId(), c.getDirId())){
										if(Long.parseLong(d.getModifyTime())>Long.parseLong(c.getModifyTime())){
											result.setUpdate(true);
											dt=new DirType(d);
											updateList.add(dt);
										}
										continue c;
									}
								}
								result.setInsert(true);
								dt=new DirType(d);
								insertList.add(dt);
							}
							
							//处理服务器数据
							s:for(DirType d:allData){
								for(DirType s:dirList){
									if(StringUtils.equals(d.getDirId(), s.getDirId())){
										if(Long.parseLong(d.getModifyTime())>Long.parseLong(s.getModifyTime())){
											syncService.delDir(s.getD_id());
											dt=new DirType(d);
											dt.setColud_id(user.getColudId());
											dt.setD_id(UUID.randomUUID().toString());
											syncService.saveDir(dt);
										}
										continue s;
									}
								}
								dt=new DirType(d);
								dt.setColud_id(user.getColudId());
								dt.setD_id(UUID.randomUUID().toString());
								syncService.saveDir(dt);
							}
						}
					}else if(StringUtils.equals("item", parseObject.getObjType())){
						//如果是在同步密码项
						List<PassItem> itemList = syncService.findPassItemByColudid(user.getColudId());
						if(content==null||content.size()==0){
							//客户端没有数据
							result.setInsert(true);
							insertList.addAll(itemList);
						}else if(itemList==null||itemList.size()==0){
							//服务器没有密码数据
							for(Object o:content){
								PassItem javaObject = JSON.toJavaObject((JSONObject)o, PassItem.class);
								javaObject.setColud_id(user.getColudId());
								javaObject.setI_id(UUID.randomUUID().toString());
								syncService.savePassItem(javaObject);
							}
						}else{
							//合并集合
							List<PassItem> allData=new ArrayList<PassItem>();
							allData.addAll(itemList);
							List<PassItem> clientData=new ArrayList<PassItem>();
							for(Object o:content){
								PassItem javaObject = JSON.toJavaObject((JSONObject)o, PassItem.class);
								allData.add(javaObject);
								clientData.add(javaObject);
							}
							PassItem pi;
							//处理客户端数据
							c:for(PassItem d:allData){
								for(PassItem c:clientData){
									if(StringUtils.equals(d.getPassId(), c.getPassId())){
										if(Long.parseLong(d.getModifyTime())>Long.parseLong(c.getModifyTime())){
											result.setUpdate(true);
											pi=new PassItem(d);
											updateList.add(pi);
										}
										continue c;
									}
								}
								result.setInsert(true);
								pi=new PassItem(d);
								insertList.add(pi);
							}
							//处理服务器数据
							s:for(PassItem d:allData){
								for(PassItem s:itemList){
									if(StringUtils.equals(d.getPassId(), s.getPassId())){
										if(Long.parseLong(d.getModifyTime())>Long.parseLong(s.getModifyTime())){
											//更新服务器
											syncService.delPassItem(s.getI_id());
											pi=new PassItem(d);
											pi.setColud_id(user.getColudId());
											pi.setI_id(UUID.randomUUID().toString());
											syncService.savePassItem(pi);
										}
										continue s;
									}
								}
								pi=new PassItem(d);
								pi.setColud_id(user.getColudId());
								pi.setI_id(UUID.randomUUID().toString());
								syncService.savePassItem(pi);
							}
						}
					}
					flag=true;
				}
				result.setInsertContent(insertList);
				result.setUpdateContent(updateList);
			}else{
				result.setFlag(false);
				result.setMsg("数据不能为空!");
			}
			
		}finally{
			result.setFlag(flag);
			result.setMsg(msg);
			String jsonString = JSON.toJSONString(result,SerializerFeature.DisableCircularReferenceDetect);
			System.out.println("响应："+jsonString);
			return jsonString;
		}
	}
}
